Skip to main content

Overview

The CoCaLoss class extends ClipLoss to support training CoCa models, which combine contrastive learning with autoregressive caption generation. It computes a weighted combination of:
  1. Contrastive loss - CLIP-style image-text matching (inherited from ClipLoss)
  2. Caption loss - Cross-entropy loss for next-token prediction in caption generation
This dual-objective training enables models to both match images with text descriptions and generate natural language captions.

Class Definition

Initialization Parameters

float
required
Weight applied to the caption generation loss. Controls the relative importance of caption quality vs. contrastive matching.
float
required
Weight applied to the contrastive loss. Set to 0 to train only the caption decoder.
int
default:"0"
Padding token ID. Positions with this token are ignored when computing caption loss.
bool
default:"False"
If True, computes contrastive loss only between local and gathered features. See ClipLoss documentation for details.
bool
default:"False"
If True, gathers features with gradient flow enabled for contrastive loss.
bool
default:"False"
If True, caches ground truth labels for contrastive loss.
int
default:"0"
Current process rank in distributed training.
int
default:"1"
Total number of processes in distributed training.
bool
default:"False"
If True, uses Horovod for distributed operations instead of torch.distributed.

Attributes

Inherits all attributes from ClipLoss, plus:
  • clip_loss_weight: Weight for contrastive loss component
  • caption_loss_weight: Weight for caption generation loss component
  • caption_loss: CrossEntropyLoss module with ignore_index=pad_id

Key Methods

forward

Computes the combined CoCa loss. Parameters:
  • image_features: Normalized contrastive image features of shape (batch_size, embed_dim)
  • text_features: Normalized contrastive text features of shape (batch_size, embed_dim)
  • logits: Caption generation logits of shape (batch_size, seq_len, vocab_size)
  • labels: Target token IDs for caption generation of shape (batch_size, seq_len)
  • logit_scale: Temperature parameter for contrastive loss (typically model.logit_scale.exp())
  • output_dict: If True, returns dict with named losses, else returns tuple
Returns:
  • If output_dict=False: Tuple of (clip_loss, caption_loss) - both weighted by their respective coefficients
  • If output_dict=True: Dictionary with keys "contrastive_loss" and "caption_loss"

Usage Example

Distributed Training Example

Dictionary Output for Logging

Caption-Only Training

Custom Loss Weighting Strategy

Monitoring Loss Components

Mathematical Formulation

The total CoCa loss is: Ltotal=w1Lcontrastive+w2Lcaption\mathcal{L}_{\text{total}} = w_1 \cdot \mathcal{L}_{\text{contrastive}} + w_2 \cdot \mathcal{L}_{\text{caption}} Where:
  1. Contrastive Loss (inherited from ClipLoss): Lcontrastive=12[CE(τIT,y)+CE(τTI,y)]\mathcal{L}_{\text{contrastive}} = \frac{1}{2}\left[\text{CE}(\tau \cdot I T^\top, y) + \text{CE}(\tau \cdot T I^\top, y)\right]
  2. Caption Loss (cross-entropy with teacher forcing): Lcaption=1Ni=1Nt=1T1[yitpad]logP(yityi<t,xi)\mathcal{L}_{\text{caption}} = -\frac{1}{N} \sum_{i=1}^{N} \sum_{t=1}^{T} \mathbb{1}[y_i^t \neq \text{pad}] \cdot \log P(y_i^t | y_i^{<t}, x_i) Where:
    • NN = batch size
    • TT = sequence length
    • yity_i^t = target token at position tt
    • xix_i = image features
    • Padding tokens are ignored via ignore_index

Hyperparameter Tuning

Recommended loss weight ratios: Guidelines:
  • Start with caption_loss_weight=2.0, clip_loss_weight=1.0
  • If captions are low quality, increase caption_loss_weight
  • If retrieval performance is poor, increase clip_loss_weight
  • Monitor both loss components separately